package com.dd.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dd.logistics.entity.Inventory;
import com.dd.logistics.entity.InventoryHistory;
import com.dd.logistics.entity.SupplierProduct;
import com.dd.logistics.mapper.InventoryHistoryMapper;
import com.dd.logistics.mapper.InventoryMapper;
import com.dd.logistics.mapper.SupplierProductMapper;
import com.dd.logistics.service.ProductInventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class ProductInventoryServiceImpl implements ProductInventoryService {
    
    @Autowired
    private InventoryMapper inventoryMapper;
    
    @Autowired
    private SupplierProductMapper supplierProductMapper;
    
    @Autowired
    private InventoryHistoryMapper historyMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inventory checkAndCreateInventory(SupplierProduct product) {
        QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", product.getId());
        Inventory inventory = inventoryMapper.selectOne(wrapper);
        
        if (inventory == null) {
            inventory = new Inventory();
            inventory.setSupplierId(product.getSupplierId());
            inventory.setProductId(product.getId());
            inventory.setQuantity(0);
            inventory.setWarningThreshold(0);
            inventoryMapper.insert(inventory);
        }
        
        return inventory;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteInventoryByProduct(Long productId) {
        QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        inventoryMapper.delete(wrapper);
    }
    
    @Transactional(rollbackFor = Exception.class)
    public Inventory createInventory(SupplierProduct product) {
        Inventory inventory = new Inventory();
        inventory.setSupplierId(product.getSupplierId());
        inventory.setProductId(product.getId());
        inventory.setQuantity(0);
        inventory.setWarningThreshold(0);
        inventoryMapper.insert(inventory);
        
        log.info("创建库存记录成功，商品ID：{}，库存ID：{}", product.getId(), inventory.getId());
        return inventory;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateQuantity(String productCode, Integer adjustQuantity) {
        log.info("更新库存数量，商品编码：{}，调整数量：{}", productCode, adjustQuantity);
        
        try {
            // 先通过商品编码查询商品
            QueryWrapper<SupplierProduct> productWrapper = new QueryWrapper<>();
            productWrapper.eq("product_code", productCode);
            SupplierProduct product = supplierProductMapper.selectOne(productWrapper);
            if (product == null) {
                throw new RuntimeException("商品编码不存在：" + productCode);
            }
            
            // 查询库存记录
            QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
            wrapper.eq("product_id", product.getId());
            Inventory inventory = inventoryMapper.selectOne(wrapper);
            
            if (inventory == null) {
                // 如果库存记录不存在，创建新记录
                inventory = new Inventory();
                inventory.setSupplierId(product.getSupplierId());
                inventory.setProductId(product.getId());
                inventory.setQuantity(0);
                inventory.setWarningThreshold(0);
                inventoryMapper.insert(inventory);
                log.info("创建新的库存记录，商品编码：{}，商品ID：{}", productCode, product.getId());
            }
            
            // 检查库存是否足够（出库时）
            if (adjustQuantity < 0 && inventory.getQuantity() + adjustQuantity < 0) {
                throw new RuntimeException("库存不足，当前库存：" + inventory.getQuantity() + 
                    "，需要出库：" + Math.abs(adjustQuantity));
            }
            
            // 更新库存
            inventory.setQuantity(inventory.getQuantity() + adjustQuantity);
            int rows = inventoryMapper.updateById(inventory);
            
            if (rows > 0) {
                // 记录历史
                InventoryHistory history = new InventoryHistory();
                history.setInventoryId(inventory.getId());
                history.setType(adjustQuantity > 0 ? "入库" : "出库");
                history.setQuantity(Math.abs(adjustQuantity));
                history.setOrderNumber(generateOrderNumber());
                historyMapper.insert(history);
                
                log.info("更新库存成功，商品编码：{}，商品ID：{}，原库存：{}，调整数量：{}，新库存：{}", 
                        productCode, product.getId(), 
                        inventory.getQuantity() - adjustQuantity,
                        adjustQuantity, 
                        inventory.getQuantity());
                
                // 检查是否需要发出库存预警
                if (inventory.getQuantity() <= inventory.getWarningThreshold()) {
                    log.warn("库存预警：商品编码：{}，当前库存：{}，预警阈值：{}", 
                            productCode, inventory.getQuantity(), inventory.getWarningThreshold());
                }
            } else {
                log.error("更新库存失败，商品编码：{}，商品ID：{}，调整数量：{}", 
                        productCode, product.getId(), adjustQuantity);
            }
            
            return rows > 0;
        } catch (Exception e) {
            log.error("更新库存异常，商品编码：{}，调整数量：{}，异常：{}", 
                    productCode, adjustQuantity, e.getMessage());
            throw new RuntimeException("更新库存失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成库存历史记录编号
     */
    private String generateOrderNumber() {
        return "IH" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) 
                + String.format("%04d", (int)(Math.random() * 10000));
    }
    
    @Override
    public boolean checkStock(Long productId, Integer quantity) {
        if (productId == null) {
            throw new RuntimeException("商品ID不能为空");
        }
        if (quantity == null) {
            throw new RuntimeException("数量不能为空");
        }
        if (quantity <= 0) {
            return true;
        }
        
        QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId)
              .select("quantity");  // 只查询需要的字段
        Inventory inventory = inventoryMapper.selectOne(wrapper);
        
        if (inventory == null) {
            log.warn("商品库存记录不存在，商品ID：{}", productId);
            return false;
        }
        
        boolean sufficient = inventory.getQuantity() >= quantity;
        if (!sufficient) {
            log.warn("库存不足，商品ID：{}，当前库存：{}，需求数量：{}", 
                    productId, inventory.getQuantity(), quantity);
        }
        
        return sufficient;
    }
} 